package handlers

import (
	"awesome-devops/applications/backend/modules/requests"
	"awesome-devops/applications/backend/modules/services"
	"awesome-devops/applications/models"
	"awesome-devops/boot"
	"fmt"
	awesomehttp "gitee.com/jjawesomejj/awesomehttp/system"
	"reflect"
	"strconv"
)

type ProjectHandler struct {
	awesomehttp.HttpBaseHandler
}

func (context *ProjectHandler) GetModuleName() string {
	return "/project/"
}
func (context *ProjectHandler) ActionAdd() interface{} {
	fmt.Println(context.HttpContext.PostData)
	projectName := context.HttpContext.PostOne("project_name").(string)
	gitUrl := context.HttpContext.PostOne("git_url").(string)
	description := context.HttpContext.PostOne("description").(string)
	branch := context.HttpContext.PostOne("branch").(string)
	project := models.Project{ProjectName: projectName,
		GitUrl:      gitUrl,
		Description: description,
		Branch:      branch,
	}
	return services.ProjectService{}.Create(project)
}

func (context *ProjectHandler) ActionSave() interface{} {
	id := requests.Input(context.HttpContext, "id", reflect.Float64).(float64)
	enableWebHook := requests.Input(context.HttpContext, "enable_web_hook", reflect.Float64).(float64)
	projectModel := models.Project{}
	projectModel.RowByID(int(id), &projectModel)
	projectModel.Labels = requests.Input(context.HttpContext, "labels", reflect.String).(string)
	projectModel.EnableWebHook = int(enableWebHook)
	projectModel.WebhookRequestKey = requests.Input(context.HttpContext, "web_hook_request_key", reflect.String, "").(string)
	res := boot.GetDbConnection().Save(&projectModel)
	return res.Error
}

func (context *ProjectHandler) ActionList() interface{} {
	page := context.HttpContext.Get("page", "").(string)
	pageSize := context.HttpContext.Get("page_size", "").(string)
	keywords := context.HttpContext.Get("keywords", "").(string)
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		pageInt = 1
	}
	pageSizeInt, err := strconv.Atoi(pageSize)
	if err != nil {
		pageSizeInt = 30
	}

	return services.ProjectService{}.List(keywords, pageInt, pageSizeInt)
}

func (context *ProjectHandler) ActionSelectList() interface{} {
	return services.ProjectService{}.SelectList()
}

func (context *ProjectHandler) ActionLabels() interface{} {
	return services.ProjectService{}.Labels()
}

func (context *ProjectHandler) ActionCommitList() interface{} {
	projectId := context.HttpContext.Get("project_id").(string)
	projectIdInt, err := strconv.Atoi(projectId)
	if err != nil {
		return err
	}
	return services.ProjectService{}.CommitList(projectIdInt)
}
